<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键词" prop="gjc">
        <el-input v-model="queryParams.gjc" placeholder="请输入关键词" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"

          @click="handleAdd"
          v-hasPermi="['archive:yqdy:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          -->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['archive:yqdy:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          -->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['archive:yqdy:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          -->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['archive:yqdy:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="yqdyList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="dyId"/>
      <el-table-column label="关键词" align="center" prop="gjc" >
        <template slot-scope="{ row }">
          <span @click="openDialog(row)" >{{ row.gjc }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="dyId">-->
<!--        <template slot-scope="scope">-->
<!--          <span style="font-weight: bold; font-size: 30px">{{ scope.$index + 1 }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="关键词" align="center" prop="gjc">-->
<!--        <template slot-scope="scope">-->
<!--          <span style="font-weight: bold; font-size: 30px; cursor: pointer" @click="openDialog(scope.row)">{{ scope.row.gjc }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="待读消息数目" align="center" prop="xxsm" >
        <template slot-scope="scope">
          <span :style="{ color: 'red' ,cursor: 'pointer'}" @click="openDialog(scope.row)" >{{ msg_display(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最新消息时间" align="center" prop="zxsj" :formatter="formatDate" />
<!--      <el-table-column label="创建人" align="center" prop="creatorId" />-->
<!--      <el-table-column label="创建时间" align="center" prop="createTime" />-->
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button

            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['archive:yqdy:edit']"
          >修改</el-button>
          <el-button

            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['archive:yqdy:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改我的订阅对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-top: 20px">
        <el-row>
          <el-button icon="el-icon-plus" @click="appendGjc">追加</el-button>
          <el-col :span="12" style="width: 72%;">
            <el-form-item label="" prop="">
              <el-input v-model="form.fragment" placeholder="" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" style="width: 90%;">
            <el-form-item label="关键词" prop="gjc">
              <el-input type="textarea" :rows="5" v-model="form.gjc" placeholder="请填入汉字、字母或阿拉伯数字，多个词用，分割" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px">
          <el-col :span="12" style="width: 90%;">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :rows="5" v-model="form.remark" placeholder="" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" :before-close="handleClose">
      <div style="padding: 20px">
        <span slot="title" style="font-weight: bold; font-size: 30px">{{ infoTitle }}</span>
<!--        <el-button icon="el-icon-refresh"  @click="resetDydaList" style="float:right;">重置</el-button>-->
        <el-table v-loading="loading" :data="yqdydaList" height="485">
          <el-table-column label="序号" type="index" :index="table_index_dyda" width="55" align="center" prop="daId" />
          <el-table-column label="标题" align="center" prop="title">
            <template slot-scope="{ row }">
              <div @dblclick="celldblclick(row)" :style="{ color: row.state == '0' ? 'red' : 'black' }">
                {{ row.title }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="密级" v-if="isFbState">
                            <template slot-scope="scope">
                              <span v-for="(i, idx) in renyuanOptions" :key="idx">
                                {{ scope.row.mj == i.dictValue ? i.dictLabel : '' }}
                            </span>
                            </template>
                        </el-table-column>
          <el-table-column label="添加时间" align="center" prop="tjsj" :formatter="formatDate" >
            <template slot-scope="{ row }">
              <div @dblclick="celldblclick(row)">
                {{ formatDate(row) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订阅" align="center" prop="dyId" v-if="false" />
        </el-table>
        <pagination
          v-show="dydaTotal>0"
          :total="dydaTotal"
          :page.sync="dydaQueryParams.pageNum"
          :limit.sync="dydaQueryParams.pageSize"
          @pagination="getDydaList"
        />
      </div>
    </el-dialog>

    <!--start  组件详情 -->
    <jianDetailsOpen v-if="jianDetailsOpen" :open="jianDetailsOpen" :celldbData="celldbData"
                     @detailsHandleClose="detailsHandleClose">
    </jianDetailsOpen>
    <!--end 组件详情 -->
    <!-- start 组卷\项目详情 -->
    <juanDetailsOpen v-if="juanDetailsOpen" :open="juanDetailsOpen" :celldbData="celldbData"
                     @detailsHandleClose="detailsHandleClose"></juanDetailsOpen>
    <!-- end 组卷\项目详情 -->
  </div>
</template>

<script>
import {
  listYqdy,
  getYqdy,
  delYqdy,
  addYqdy,
  updateYqdy,
  getCategoryId,
  updateState,
  getthbytreenodeHeaderList
} from "@/api/archive/liyong/dingyue/yqdy";
import jianDetailsOpen from '@/components/componentsJianDetails/index.vue' //件详情
import juanDetailsOpen from '@/components/componentsJuanDetails/index.vue'
import fileTrees from "@/components/fileTrees/index.vue"
import queryCriteriaList from "@/components/queryCriteriaList/index.vue"
import tableList from "@/components/tableList/index.vue";
import treeHeight from "@/mixins/treeHeight";
import {getLastIndexOf} from "@/utils";
import log from "@/views/monitor/job/log.vue";
import { getDicts_archive } from '@/api/archive/dict/dictManageData'
import { fbstat } from "@/api/archive/fileCollection/offlinReception.js";
import {
  getdamjbyrymj
} from "@/api/archive/fileCollection/offlinReception.js";
export default {
  name: "Yqdy",
  mixins: [treeHeight], // 混入方法
  components: {
    queryCriteriaList,
    // fileTrees,
    tableList,
    jianDetailsOpen,
    juanDetailsOpen
  },
  data() {
    const checkGjc = (rule, value, callback) => {
      if (value) {
        if(value.length > 80){
          return callback(new Error('最多输入80个字!'))
        }
        var reg = /^(?!.*,$)(?!^，|.*，{2})[\w，\u4e00-\u9fa5]+(?<!，)$/;
        if (reg.test(value) === false) {
          return callback(new Error('请填入汉字、字母或阿拉伯数字，多个词请用中文逗号（，）分割，不能含有以下特殊字符：! @ # $ ￥ % …… ^ & ? * , . 。 : ; " < >（） / |及空格，开头和结尾不能为中文逗号（，）'))
        }
      }
      callback()
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      dydaTotal: 0,
      dyId: 0,
      categoryId: 0,
      // 我的订阅表格数据
      yqdyList: [],
      yqdydaList: [],
      // 弹出层标题
      title: "",
      infoTitle:"",
      // 是否显示弹出层
      open: false,
      dialogVisible: false,
      selectedRow: null,
      jianDetailsOpen: false,//件详情弹窗
      juanDetailsOpen: false,//卷详情弹窗
      // 查询参数
      // dyId: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gjc: null,
        xxsm: null,
        zxsj: null,
        creatorId: null,
        createTime: null,
        remark: null,
        menuId: null
      },
      dydaQueryParams: {
        pageNum: 1,
        pageSize: 10,
        dyId: 0,
        gjc:0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        gjc: [
          { required: true, message: "关键词不能为空", trigger: "blur" },
          { required: true, trigger: 'blur', validator: checkGjc }
        ]
      },
      isFbState:false
    };
  },
  created() {
    this.getList();
    fbstat().then(res => {  //false=不是分保，true=是分保
      this.isFbState = res.data
      if (this.isFbState) {
        //密级下拉列表
        getDicts_archive("MJ").then(res => { //人员密级
          getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
            var mjdata = [];
            for (var i in resdata.data) {
              for (var j in res.data) {
                if (resdata.data[i].daMj == res.data[j].dictValue) {
                  mjdata.push(res.data[j])
                }
              }
            }

            this.renyuanOptions = mjdata
          })
        })
      }
    })
  },
  methods: {
    table_index(index){
      return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
    },
    table_index_dyda(index){
      return (this.dydaQueryParams.pageNum-1) * this.dydaQueryParams.pageSize + index + 1;
    },
    msg_display(row){
      const xxsm = row.xxsm;
      if (xxsm == 0 ){
        return "未知";
      }
      return `新增${xxsm}条`;
    },
    formatDate(row, column) {
      let date;
      if (row.hasOwnProperty('zxsj')){
        if (row.zxsj==null){
          return "";
        }
        date = new Date(row.zxsj);
      }else {
        date = new Date(row.tjsj);
      }
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    openDialog(row) {
      this.selectedRow = row;
      this.infoTitle = "关键词："+this.selectedRow.gjc;
      if (this.selectedRow.dyId !== null && this.selectedRow.dyId !== undefined) {
        this.dydaQueryParams.dyId = this.selectedRow.dyId;
      }
      // this.dydaQueryParams.dyId = this.selectedRow.dyId;
      this.getDydaList();
      this.dialogVisible = true;
    },
    /** 查询我的订阅列表 */
    getList() {
      // this.loading = true;
      this.queryParams.menuId = this.$route.meta.menuId;
      listYqdy(this.queryParams).then(response => {
        this.yqdyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询我的订阅详情列表 */
    getDydaList() {
      // this.loading = true;
      getYqdy(this.dydaQueryParams).then(response => {
        this.yqdydaList = response.rows;
        this.dydaTotal = response.total;
        this.loading = false;
        // if ( response.rows[0].dyId !== null && response.rows[0].dyId !== undefined ){
        //   this.dydaQueryParams.dyId = response.rows[0].dyId;
        // }
      });
      // this.dydaQueryParams.dyId = 0;
      // this.dydaQueryParams.gjc = 0;
    },
    //双击列表进入详情页面
    celldblclick(row) {
      var level = row.type;
      // row.dyId = this.dydaQueryParams.dyId;
      // var categoryId = 0;
      // var subTableName = row.subTableName;
      getCategoryId({ subTableName: row.subTableName,dyId:row.dyId,daId:row.daId }).then(response => {
        console.log(response)
        if (response.code == '200') {
          this.categoryId = response.data;
          getthbytreenodeHeaderList(
            {
              categoryId: this.categoryId, menuId: this.$route.meta.menuId, subTableName: row.subTableName
            }
          ).then(response => {
            var tableHeaderList = response.rows
            this.celldbData = {
              id: row.daId,
              categoryId: this.categoryId,
              menuId: this.$route.meta.menuId,
              sub_table_name: row.subTableName,
              label: "详情",
              level: level,
              ifSub_table_name: row.subTableName,
              isDel: "0",  //判断是回收站数据还是接收收据 isDel:1  回收站    isDel:0 //离线接收、档案接收、在线接收
              tableHeaderList: tableHeaderList,
              isBorrowingCar:row.is_borrowing_car
            }
            console.log("==================:"+this.celldbData);
            this.$nextTick(() => {
              if (level == 0) {  //F 进入件详情
                this.jianDetailsOpen = true;
              } else { //进入卷详情 和项目详情
                this.juanDetailsOpen = true
              }
            })
            if (row.state == 0){
              updateState(row);
              this.getList();
              this.getDydaList();
            }
          });
        }
      }).catch(()=>{
        this.resetDydaList();
        this.resetQuery();
      });
    },
    //关闭详情页面
    detailsHandleClose() {
      // this.categoryId = null;
      this.jianDetailsOpen = false;
      this.juanDetailsOpen = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();

    },
    // 表单重置
    reset() {
      this.form = {
        dyId: null,
        gjc: null,
        xxsm: null,
        zxsj: null,
        creatorId: null,
        createTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetDydaList() {
      this.dydaQueryParams.pageNum=1;
      this.dydaQueryParams.pageSize=10;
      this.getDydaList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dyId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订阅";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dyId = row.dyId || this.ids
      getYqdy(dyId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改我的订阅";
      });
    },
    appendGjc() {
      if (this.form.fragment!=undefined&&this.form.fragment!=""){
        if(this.form.gjc==null||this.form.gjc==""){
          this.form.gjc=this.form.fragment
        }else {
          if(this.form.gjc.slice(-1)=="，"){
            this.form.gjc=this.form.gjc+this.form.fragment
          }else {
            this.form.gjc=this.form.gjc+"，"+this.form.fragment
          }
        }
        this.form.fragment = ""
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dyId != null) {
            updateYqdy(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addYqdy(this.form).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.open = false;
              var row = {
                gjc: this.form.gjc
              };
              this.dydaQueryParams.gjc = this.form.gjc;
              // this.openDialog(row);
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dyIds = row.dyId || this.ids;
      const gjc = row.gjc || this.gjc;
      this.$modal.confirm('是否确认删除关键词为"' + gjc + '"的数据项？').then(function() {
        return delYqdy(dyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('archive/yqdy/export', {
        ...this.queryParams
      }, `yqdy_${new Date().getTime()}.xlsx`)
    },
    handleClose() {
      this.dydaQueryParams= {
        pageNum: 1,
        pageSize: 10,
        dyId: 0,
        gjc:0
      }
      this.dialogVisible = false
    }
  }
};
</script>
